<template>
  <div class="supplement-selection">
      <a-alert
        message="补选说明"
        description="补选阶段只能选择有空余名额且您未选的课程，请谨慎操作。"
        type="info"
        showIcon
        style="margin-bottom: 16px;"
      />
      
      <div class="selection-toolbar">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-input-search
              placeholder="按课程名称、教师搜索"
              @search="handleSearch"
              enterButton
              v-model="searchValue"
            />
          </a-col>
          <a-col :span="12">
            <a-button @click="refreshCourses" style="float: right;">
              <a-icon type="sync" />刷新
            </a-button>
          </a-col>
        </a-row>
      </div>

      <a-table
        :columns="columns"
        :dataSource="filteredCourses"
        rowKey="id"
        :pagination="pagination"
        :loading="loading"
      >
        <span slot="timeLocation" slot-scope="text, record">
          <div>{{ record.time }}</div>
          <div>{{ record.location }}</div>
        </span>

        <span slot="vacancy" slot-scope="text, record">
          <a-tag :color="record.vacancy > 0 ? 'green' : 'red'">
            {{ record.vacancy }}
          </a-tag>
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button 
            type="primary" 
            size="small"
            @click="handleSelect(record)"
            :disabled="record.vacancy <= 0"
          >
            补选
          </a-button>
          <a-tooltip v-if="record.vacancy <= 0" title="该课程已无空余名额">
            <a-icon type="question-circle" style="margin-left: 8px" />
          </a-tooltip>
        </span>
      </a-table>
  </div>
</template>

<script>
const columns = [
  {
    title: '课程编号',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '课程名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '学分',
    dataIndex: 'credit',
    key: 'credit',
    width: 80
  },
  {
    title: '任课教师',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120
  },
  {
    title: '时间/地点',
    key: 'timeLocation',
    scopedSlots: { customRender: 'timeLocation' },
    width: 180
  },
  {
    title: '空余名额',
    key: 'vacancy',
    scopedSlots: { customRender: 'vacancy' },
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 100
  }
];

export default {
  data() {
    return {
      columns,
      courses: [],
      filteredCourses: [],
      loading: false,
      searchValue: '',
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: total => `共 ${total} 门可补选课程`
      },
      selectedCourses: []
    };
  },
  created() {
    this.fetchCourses();
    this.fetchSelectedCourses();
  },
  methods: {
    fetchCourses() {
      this.loading = true;
      // 模拟API调用
      setTimeout(() => {
        this.courses = this.generateMockCourses();
        this.filterCourses();
        this.pagination.total = this.filteredCourses.length;
        this.loading = false;
      }, 500);
    },
    
    generateMockCourses() {
      return [
        {
          id: "CS101",
          name: "计算机科学导论",
          credit: 3,
          teacher: "张明华",
          time: "周一 1-3节",
          location: "2号教学楼",
          capacity: 60,
          enrolled: 58,
          vacancy: 2
        },
        {
          id: "CS302",
          name: "数据结构与算法",
          credit: 4,
          teacher: "张明华",
          time: "周五 1-4节",
          location: "1号教学楼",
          capacity: 50,
          enrolled: 48,
          vacancy: 2
        },
        {
          id: "MATH305",
          name: "线性代数",
          credit: 3,
          teacher: "李红梅",
          time: "周一 8-10节",
          location: "1号教学楼",
          capacity: 70,
          enrolled: 68,
          vacancy: 2
        },
      ];
    },
    fetchSelectedCourses() {
      // 这里应该是真实的API调用
      // 模拟获取已选课
      setTimeout(() => {
        this.selectedCourses = [
          { id: 'C2001', name: '已选PLC与工业控制技术' },
          { id: 'C2005', name: '已选课程2' }
        ];
        this.filterCourses();
      }, 300);
    },
    
    filterCourses() {
      let filtered = this.courses;
      
      // 按搜索条件过滤
      if (this.searchValue) {
        const lowerSearch = this.searchValue.toLowerCase();
        filtered = filtered.filter(c => 
          c.name.toLowerCase().includes(lowerSearch) || 
          c.teacher.toLowerCase().includes(lowerSearch)
        );
      }
      
      // 过滤掉已选课程
      filtered = filtered.filter(c => 
        !this.selectedCourses.some(sc => sc.id === c.id)
      );
      
      this.filteredCourses = filtered;
    },
    
    handleSearch(value) {
      this.searchValue = value;
      this.filterCourses();
    },
    
    refreshCourses() {
      this.fetchCourses();
    },
    
   handleSelect(course) {
     this.$confirm({
       title: '确认补选该课程吗?',
       content: `课程名称: ${course.name}\n任课教师: ${course.teacher}\n上课时间: ${course.time}`,
       onOk: () => {
         this.loading = true;
         // 模拟API调用
         setTimeout(() => {
           // 模拟补选成功
           const success = Math.random() > 0.1; // 90%成功率
           
           if (success) {
             // 更新课程空余名额
             const updatedCourses = this.courses.map(c => {
               if (c.id === course.id) {
                 return {
                   ...c,
                   vacancy: c.vacancy - 1,
                   enrolled: c.enrolled + 1
                 };
               }
               return c;
             });
             
             this.courses = updatedCourses;
             this.selectedCourses.push(course);
             this.filterCourses();
             
             this.$message.success(`成功补选课程: ${course.name}`);
             this.$emit('select', course);
             
             // 更新分页总数
             this.pagination.total = this.filteredCourses.length;
           } else {
             // 模拟补选失败
             this.$message.error(`补选失败: ${course.name} 已无空余名额`);
             
             // 刷新课程数据
             this.fetchCourses();
           }
           
           this.loading = false;
         }, 800);
       },
       onCancel() {
         this.$message.info('已取消补选操作');
       }
     });
   }
  }
};
</script>

<style scoped>
.supplement-selection {
  margin: 0;
  padding:20px;
}
.selection-toolbar {
  margin-bottom: 16px;
}
</style>